const { Add, Query, Update, QueryOne, Exec, QueryList_Page, Exec_Count, ExecGetOne, QueryById } = require('../db/dbhelper');
var { init, format, filObj } = require('../models/people');
var persondes = require('../models/persondes');
const taskAdd = require('./tasktodo').taskAdd;
var { ossfileUpdatePcode } = require('./ossfile');
var _  = require('underscore');
var { formatDate, formatDateTime, formatDateYear, getAge, getStar, formatDateYearMonth } = require('../libs/common');
var { xlsxParse, exportParse } = require('../libs/xlsx');
var { getfilePath } = require('../libs/file');
var { persondesList, persondesImport, persondesQueryOne } = require('./persondes');
var personlabelQueryOne = require('./personlabel').personlabelQueryOne;
var { accessrecordAdd } = require('./accessrecord');
var { dailyDone } = require('../services/dailyuser');
const logger = require('../libs/log').logger;
var { sendMsg } = require('./wechat');
var moment = require('moment');

//保存用户
const peopleSave = async function (doc) {
  try {
    delete doc.synopsis;
    delete doc.isschool;
    delete doc.iscompany;
    delete doc.islocal;
    delete doc.issecret;
    delete doc.isopen;
    delete doc.islook;
    delete doc.avator;
    logger.info(`-------peopleSave------doc:`, doc)
    if (!doc.code) {
      return {
        code: 1,
        msg: '请退出小程序重新进入'
      }
    }
    let result;
    if (doc.grender) {
      if (!doc.phone) {
        result = {
          code: 1,
          msg: '请授权手机号'
        }
      }
      if (!doc.ideal_partner || !doc.ideal_partner.remarks) {
        result = {
          code: 1,
          msg: '请填写理想的另一半'
        }
      }
      if (!doc.self_description || !doc.self_description.remarks) {
        result = {
          code: 1,
          msg: '请填写自我描述'
        }
      }
      if (!doc.position) {
        result = {
          code: 1,
          msg: '请选择职业或行业'
        }
      }
      if (!doc.company) {
        result = {
          code: 1,
          msg: '请填写公司名称'
        }
      }
      if (!doc.university) {
        result = {
          code: 1,
          msg: '请填写毕业院校'
        }
      }
      if (!doc.nickname || doc.nickname.indexOf('红豆家缘') >= 0) {
        result = {
          code: 1,
          msg: '请填写个性化昵称'
        }
      }
      if (!doc.nickname || doc.nickname.indexOf('豆号') >= 0) {
        result = {
          code: 1,
          msg: '请填写个性化昵称'
        }
      }
      if (doc.identity == '家长' && !doc.name){
        result = {
          code: 1,
          msg: '请填写孩子姓名'
        }
      }
      // 判断是否上传相册
      let photo = await QueryOne('hzz_ossfiles',{pcode: doc.code, type:'个人相册'});
      if(!photo){
        result = {
          code: 1,
          msg: '请上传个人相册'
        }
      }
    }

    let newdoc = {};
    let userdata;
    if (doc.connection) {
      doc.loginip = doc.connection.remoteAddress;
    }
    if (doc.birthday) {// 根据出生日期计算年龄
      if (new Date().getTime() < new Date(doc.birthday).getTime()) {
        result = {
          code: 1,
          msg: '出生日期不能比当前日期大'
        }
      } else {
        doc.age = getAge(doc.birthday);
        doc.star = getStar(doc.birthday);
      }
    }

    userdata = await QueryOne('hzz_peoples', { code: doc.code }, 'id,code,invitcode,isinviter,avator,phone,grade');
    if (userdata) {
      doc.id = userdata.id;

      if (doc.identity == '本人' || doc.identity == '家长') {
        doc.isfirst = 0;
        doc.is_father = doc.identity == '家长' ? 1 : 0;
      }
      if (!!doc.grender && doc.cross_realname_auth == 1 && !result) {
        doc.issave = 1;
      }
      doc.grade = userdata.grade;
      // 判断手机号和相册是否填写，更新认证进度
      if(doc.phone && !userdata.phone){
        doc.grade = doc.grade + 1;
      }
      if(doc.avator && (userdata.avator == null || userdata.avator == 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' || userdata.avator == 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png')){
        doc.grade = doc.grade + 1;
      }
      newdoc = format(doc);
      logger.info(`-------peopleSave------newdoc:`, newdoc)
      await Update('hzz_peoples', newdoc);
      // 保存关于我
      // -自我描述
      logger.info(`-------peopleSave------doc:`, doc)
      if (doc.self_description) {
        let des_self = doc.self_description;
        des_self.pcode = doc.code;
        des_self.type = 'self_description';
        let pl = await QueryOne('hzz_persondes', { pcode: doc.code, type: 'self_description' }, null);
        logger.info(`-------peopleSave---plplpl---pl:`, pl)
        if (pl) {
          des_self.id = pl.id;
          await Update('hzz_persondes', persondes.format(des_self));
        } else {
          await Add('hzz_persondes', persondes.init(des_self));
        }
      }
      // -理想另一半
      if (doc.ideal_partner) {
        let des_partner = doc.ideal_partner;
        des_partner.pcode = doc.code;
        des_partner.type = 'ideal_partner';
        let pl = await QueryOne('hzz_persondes', { pcode: doc.code, type: 'ideal_partner' }, null);
        logger.info(`-------peopleSave---plplpl---pl:`, pl)
        if (pl) {
          des_partner.id = pl.id;
          await Update('hzz_persondes', persondes.format(des_partner));
        } else {
          await Add('hzz_persondes', persondes.init(des_partner));
        }
      }
      logger.info(`-------peopleSave------result11:`, result)
      if (!result) {
        // 用户保存个人资料，给推荐人发送确认信息并创建待办--5分钟后提醒
        if (doc.nickname && doc.grender && doc.phone) {
          if (userdata.invitcode) {
            var timernull = setInterval(function () {
              clearInterval(timer);
              clearInterval(timernull);
              logger.error(`-------发送用户待办失败-----`)
            }, 1000 * 600)
            var timer = setInterval(function () {
              sendToInviter(userdata.invitcode, doc.code, timer, timernull);
            }, 60000)
          }
        }
        result = {
          code: 0,
          data: doc.code,
          msg: '保存成功'
        }
      }
    } else {
      result = {
        code: 1,
        msg: '请退出小程序重新进入'
      }
    }
    logger.info(`-------peopleSave------result22:`, result)
    return result;
  } catch (error) {
    logger.info(`-------peopleSave------error:`, error)
    return {
      code: 1,
      msg: error ? error.message : '保存失败'
    }
  }
}

async function sendToInviter(invitcode, pcode, timer, timernull) {
  let task = await QueryOne('hzz_tasktodos', { name: '用户确认', pcode: invitcode, gcode: pcode });
  if (task) {
    clearInterval(timer);
    clearInterval(timernull);
    return;
  }
  taskAdd({ name: '用户确认', pcode: invitcode, gcode: pcode });
  let peo = await QueryOne('hzz_peoples', { code: pcode }, 'openid,code,phone,nickname');
  if (peo) {
    // 发送提醒消息 
    let send_data = {
      "first": {
        "value": "您好，您的业务有新进展！",
        "color": "#173177"
      },
      "keyword1": {
        "value": "新用户确认",
        "color": "#173177"
      },
      "keyword2": {
        "value": `您邀请的[${peo.nickname}]已入驻小程序，快去看看是TA吗？`,
        "color": "#e8320e"
      },
      "remark": {
        "value": "前往'消息-我的待办'查看，感谢您的支持",
        "color": "#173177"
      }
    };
    let send_data_red = {
      "thing2": {
        "value": `您邀请的[${peo.nickname}]已入驻小程序，快去看看是TA吗？`
      },
      "time1": {
        "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
      }
    };
    sendMsg('user_confirm', send_data, invitcode, "pages/message/message",send_data_red); //  我的消息
    clearInterval(timer);
    clearInterval(timernull);
  }
}

//保存用户-后台
const peopleSaveBack = async function (doc) {
  try {
    logger.info(`-------peopleSaveBack------doc:`, doc)
    let newdoc = {};
    let userdata = {};
    if (doc.code) {
      userdata = await QueryOne('hzz_peoples', { code: doc.code }, 'id,code');
      if (userdata) {
        doc.id = userdata.id;
        newdoc = format(doc);
        logger.info(`-------peopleSaveBack------newdoc:`, newdoc)
        await Update('hzz_peoples', newdoc);
        // 保存关于我
        // -自我描述
        if (doc.self_description) {
          let des_self = doc.self_description;
          des_self.type= 'self_description';
          des_self.pcode = doc.code;
          let pl = await QueryOne('hzz_persondes', { pcode: des_self.pcode, type: des_self.type }, null);
          logger.info(`-------peopleSaveBack------pl:`, pl)
          if (pl) {
            des_self.id = pl.id;
            await Update('hzz_persondes', persondes.format(des_self));
          } else {
            await Add('hzz_persondes', persondes.init(des_self));
          }
        }
        // -理想另一半
        if (doc.ideal_partner) {
          let des_partner = doc.ideal_partner;
          des_partner.type= 'ideal_partner';
          des_partner.pcode = doc.code;
          let pl2 = await QueryOne('hzz_persondes', { pcode: des_partner.pcode, type: des_partner.type }, null);
          logger.info(`-------peopleSaveBack------pl2:`, pl2)
          if (pl2) {
            des_partner.id = pl2.id;
            await Update('hzz_persondes', persondes.format(des_partner));
          } else {
            await Add('hzz_persondes', persondes.init(des_partner));
          }
        }
        return {
          code: 0,
          msg: '修改用户信息成功'
        }
      }
    }
    // 新增
    doc.sourcetype='后台录入';
    doc.userstate = 1;
    doc.confirm = 1;
    doc.identity = '本人';
    doc.cross_realname_auth = 1;
    doc.level=1;
    newdoc = init(doc);
    logger.info(`-------peopleSaveBack------newdoc-----init:`, newdoc)
    userdata = await Add('hzz_peoples', newdoc);
    logger.info(`-------peopleSaveBack------newdoc-----userdata:`, userdata)
    // 保存关于我
    // -自我描述
    if (doc.self_description) {
      let des_self = doc.self_description;
      des_self.type= 'self_description';
      des_self.pcode = userdata.code;
      let pl = await QueryOne('hzz_persondes', { pcode: des_self.pcode, type: des_self.type }, null);
      if (pl) {
        des_self.id = pl.id;
        await Update('hzz_persondes', persondes.format(des_self));
      } else {
        await Add('hzz_persondes', persondes.init(des_self));
      }
    }
    // -理想另一半
    if (doc.ideal_partner) {
      let des_partner = doc.ideal_partner;
      des_partner.type= 'ideal_partner';
      des_partner.pcode = userdata.code;
      let pl = await QueryOne('hzz_persondes', { pcode: des_partner.pcode, type: des_partner.type }, null);
      if (pl) {
        des_partner.id = pl.id;
        await Update('hzz_persondes', persondes.format(des_partner));
      } else {
        await Add('hzz_persondes', persondes.init(des_partner));
      }
    }

    return {
      code: 0,
      data: userdata.code,
      msg: '新增用户信息成功'
    }
  } catch (error) {
    logger.info(`-------peopleSaveBack------error:`, error)
    return {
      code: 1,
      msg: error ? error.message : '保存失败'
    }
  }
}

//用户列表
const peopleList = async function (doc) {
  try {
    logger.info('-------peopleList---doc------:', doc)
    let pcode = doc.pcode;
    let resList = await getPeopleList(doc, 0);
    // logger.info('-------peopleList---resList:', resList)
    let myData = await QueryOne('hzz_peoples', { code: pcode }, 'issecret,company');
    if(!myData){
      return {
        code: 1,
        msg: '用户已注销'
      };
    }
    let { total, pagecount, listData, pagenum, pagesize } = resList;
    let list = [];
    for (let index = 0; index < listData.length; index++) {
      let item = listData[index];
      if (item && item.nickname && item.nickname.length > 10) {
        item.nickname = item.nickname.substr(0, 10);
      }
      item.nickname += `(${item.is_father ? '家长' : '本人'})`;
      item.birthdayStr = formatDateYear(item.birthday);
      delete item.birthday;
      let tjr = await QueryOne('hzz_peoples', { code: item.invitcode }, 'nickname,avator,code');
      item.inviter = tjr || {};
      // item.avator = item.avator ? item.avator : ali_oss.headimg;
      if (item.islocal) {//隐藏位置信息
        item.city = '******';
        item.province_town = '******';
      }
      item.university = item.university || '';
      item.position = item.position || '';
      // 查询是否收藏此用户
      let fens = await QueryOne('hzz_peoplefans', { pcode: item.code, fcode: pcode, state: 1 });
      item.isfans = !!fens ? 1 : 0;
      // 隐私管理
      {
        if (item.isschool) {
          item.university = '******';
        }
        if (item.iscompany) {
          item.company = '******';
        }
        if (item.islocal) {
          item.province = '******';
          item.city = '******';
          item.province_town = '******';
          item.city_town = '******';
        }
        // 相册不公开，获取有没有申请过，是否通过
        if (item.islook) {
          let tododata = await QueryOne('hzz_tasktodos', { name: '相册解锁', pcode: item.code, gcode: pcode, status: 1 });
          if (tododata) {
            item.islook = 0;
          }
          if (pcode == item.invitcode) {
            item.islook = 0;
          }
        }
        if (item.issecret || (myData && myData.issecret)) {
          if (myData && item.company == myData.company) {
            // 同公司不显示
          } else {
            list.push(item);
          }
        } else {
          list.push(item);
        }
      }

      // 自我描述返回
      // 获取用户描述

      let desList = await persondesList({ pcode: item.code });
      let selfData = _.find(desList, (x) => {
        return x.type == 'self_description';
      })
      let ideaData = _.find(desList, (x) => {
        return x.type == 'ideal_partner';
      })
      item.description = selfData && selfData.remarks ? selfData.remarks : (ideaData && ideaData.remarks ? ideaData.remarks : '本人相貌清纯可爱，温柔善良，通情达理，善解人意。人品好，三观正，有爱心，无不良嗜好。');
      item.description = item.description.length > 50 ? item.description.substr(0, 50) + '...' : item.description;
      // 用户没有头像，采用默认头像
      if (!item.avator) {
        item.avator = item.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
      }
    }
    
    let result =  {
      code: 0,
      data: {
        list,
        total,
        pagecount,
        pagenum,
        pagesize
      },
      msg: '获取成功'
    };
    logger.info('-------peopleList---result:', JSON.stringify(result))
    return result;
  } catch (error) {
    logger.info('-------peopleList---error:', error)
    return {
      code: 1,
      msg: '获取失败'
    }
  }
}
var { resetdata, reshour } = require('../../server_config.json').sys_config;
const getPeopleList = async function (doc, time) {
  let { pagenum, pagesize, pcode } = doc;
  pagenum = pagenum || 1;
  pagesize = pagesize || 5;
  

  let selectStr = 'invitcode,code,phone,nickname,avator,grender,birthday,age,height,city,education,isopen,islook,issecret,isschool,iscompany,islocal,is_father,house,car,marry,star,university,position';
  let sql = `SELECT ${selectStr} FROM hzz_peoples  `;
  // 优先查询每日系统推荐用户
  let now = new Date();
  let builddate = formatDate(now);
  let hour = now.getHours();
  let sqldaily;
  logger.info(`---------getPeopleList-------pagenum:${pagenum}-pagesize:${pagesize}---time:${time}`);
  logger.info('当天有取当天的，当天没有，每日9点前取数还取前一天的:hour1111111111'+hour,reshour+'--'+builddate);
  // 当天有取当天的，当天没有，每日9点前取数还取前一天的
 
  if (hour < reshour) {
    let count = (await ExecGetOne(`select count(1) as total from hzz_dailyusers where pcode='${pcode}' AND builddate= '${builddate}' AND tcode IS NOT NULL`)).total
    if (count == 0) {
      let resetDate = now.setDate(now.getDate() - 1);
      builddate = formatDate(new Date(resetDate));
    }
  }
  sqldaily = `select DISTINCT tcode,source,isout from hzz_dailyusers where pcode='${pcode}' AND builddate= '${builddate}' AND tcode IS NOT NULL ORDER BY id DESC`;
  // if(pcode =='871981590103'){
  //   if (hour < reshour) {
  //     let count = (await ExecGetOne(`select count(1) as total from hzz_dailyusers where builddate= '${builddate}' AND tcode IS NOT NULL`)).total
  //     if (count == 0) {
  //       let resetDate = now.setDate(now.getDate() - 1);
  //       builddate = formatDate(new Date(resetDate));
  //     }
  //   }
  //   sqldaily = `select DISTINCT tcode from hzz_dailyusers where  builddate= '${builddate}' AND tcode IS NOT NULL ORDER BY id DESC`;
  // }
  sqldaily += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
  let dailyList = await Exec(sqldaily);
  let sqltotal = '';
  // 有推荐用户直接返回
  logger.info('有推荐用户直接返回',dailyList.length);
  
  
  if (dailyList.length > 0) {
    let tcodes = _.compact(_.pluck(dailyList, 'tcode')).join(',');
    sqltotal = `select count(1) as total from hzz_dailyusers where pcode='${pcode}' AND builddate= '${builddate}' AND tcode IS NOT NULL `;
    // if(pcode =='871981590103'){
    //   sqltotal = `select count(1) as total from hzz_dailyusers where  builddate= '${builddate}' AND tcode IS NOT NULL `;
    // }
    sql += ` where code IN (${tcodes})`;
    let total = (await ExecGetOne(sqltotal)).total;
    let pagecount = Math.ceil(total / pagesize);
    let listData = await Exec(sql);

    ///let orderUsers = await Exec(`select * from hzz_orders where  pcode IN (${tcodes})`);//signtime>'${builddate+' 00:00:00'}' AND  signtime<'${builddate+' 23:59:59'}' and
    for (let index = 0; index < dailyList.length; index++) {
      const d = dailyList[index];
      // let peo = _.find(listData, (p) => {
      //   return p.code == d.tcode;
      // });
      // 获取用户签到码
      // let orderUser = await ExecGetOne(`select * from hzz_orders where pcode ='${d.tcode}' and activeid=10  ORDER BY id DESC LIMIT 1`);
      // if(orderUser){
      //   peo.num = orderUser.num;
      // }
      if(d.isout==0){
        Update('hzz_dailyusers', {id: d.id, isout: 1, updatetime: new Date()});
      }
    }
    // let listData= _.map(dailyList, (d) => {
    //   let peo = _.find(rdata, (p) => {
    //     return p.code == d.tcode;
    //   });
    //   // 获取用户签到码
    //   let orderUser = await ExecGetOne(`select * from hzz_orders where pcode =${d.tcode} and source = ${d.source}`);
    //   if(orderUsers && orderUsers.length>0){
    //     let orderUser = _.find(orderUsers,(x)=>{
    //       return x.pcode == d.tcode;
    //     });
    //     if(orderUser){
    //       peo.num = orderUser.num;
    //     }
    //   }
      
    //   // if(d.isout==0){
    //   //   Update('hzz_dailyusers', {id: d.id, isout: 1, updatetime: new Date()});
    //   // }
    //   return JSON.parse(JSON.stringify(peo));
    // })
    return {
      total, pagecount, listData, pagenum, pagesize,
    }
  } else {
    logger.info('无系统用户，调用每日生成推荐用户方法生成今日用户11111111111',time);
    if (time == 0) {
      logger.info('无系统用户，调用每日生成推荐用户方法生成今日用户',time);
      // 无系统用户，调用每日生成推荐用户方法生成今日用户
      await dailyDone({ code: pcode });
      return getPeopleList(doc, 1);
    } else {
      return {
        total: 0,
        pagecount: 1,
        pagenum: 1,
        pagesize: pagesize,
        listData: []
      }
    }
  }
}

//用户列表-后台专用
const peopleListBack = async function (req) {
  try {
    let { userphone, userrole } = req.headers;
    let isenterprise = userrole ? userrole.split(',').includes('enterprise'): false;
    let { filter, select, pagenum, pagesize } = req.body;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let sql = `SELECT * FROM hzz_peoples  WHERE 1=1 AND (level<>9 OR userstate<>9) `;
    let sql_count = `SELECT count(1) as total FROM hzz_peoples  WHERE 1=1 AND (level<>9 OR userstate<>9) `;
    let sql_filter = '';
    // 如果是外联合作推荐人角色，并且绑定手机号的，只查询自己用户信息
    if(isenterprise && userphone){
      let da1= await ExecGetOne(`select pcode from hzz_inviterhistories where phone ='${userphone}'`);
      if(da1){
        sql_filter +=` AND invitcode ='${da1.pcode}' ` 
      }
    }
    if (filter) {
      for (const key in filter) {
        if (Object.hasOwnProperty.call(filter, key)) {
          const val = filter[key];
          if ((val || val==0) && val!='') {
            if (key == 'nickname' || key == 'phone') {
              if (key == 'nickname') {
                sql_filter += ` AND (${key} like '%${val}%' OR name like '%${val}%' OR name_father like '%${val}%')`;
              } else {
                sql_filter += ` AND ${key} like '%${val}%' `;
              }
            } else if (key == 'level') {
              sql_filter += ` AND ${key} >=${val}`;
            } else if (key == 'grender') {
              sql_filter += ` AND ${key} ='${val}'`;
            } else if (key == 'isphoto') {
              if(val==1)
                sql_filter += ` AND avator  is not null and avator<>'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png'`;
              else 
                sql_filter += ` AND (avator  is null OR avator = 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png')`;
            } else if(key == 'birthdayStart'){
              sql_filter += ` AND birthday >= '${val+'-01-01'}'`;
            } else if(key == 'birthdayEnd'){
              sql_filter += ` AND birthday <= '${val+'-12-31'}'`;
            } else if(key == 'heightStart'){
              sql_filter += ` AND height >= '${val}'`;
            } else if(key == 'heightEnd'){
              sql_filter += ` AND height <= '${val}'`;
            } else if(key == 'education_code'){
              sql_filter += ` AND education_code >= '${val}'`;
            } else if(key == 'position'){
              sql_filter += ` AND position IN ("${val.join('","')}")`;
            } else if(key == 'city_town'){
              sql_filter += ` AND (city_town ="${val}" OR city = "${val}" OR city_account= "${val}" )`;
            } else if(key == 'area_town' && val!='市辖区'){
              sql_filter += ` AND (area_town ="${val}" OR area = "${val}" OR area_account= "${val}" )`;
            } else {
              sql_filter += ` AND ${key} ='${val}'`;
            }
          }
        }
      }
    }
    sql_count += sql_filter;
    sql += sql_filter;
    sql += ' ORDER BY grade DESC, updatetime DESC, online ASC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let list = await Exec(sql);
    let pcodes = _.compact(_.union(_.pluck(list, 'inviter_code'), _.pluck(list, 'invitcode')));
    let plist = [];
    if (pcodes && pcodes.length) {
      plist = await Exec(`select nickname,name,name_father,code,is_father from hzz_peoples where code in(${pcodes.join(',')})`)
    }

     // 获取当前用户文件
     let fileList =[];
     let peo_codes = _.pluck(list, 'code');
     if (peo_codes && peo_codes.length) {
      let execsql = `SELECT * FROM hzz_ossfiles WHERE type='个人相册' AND url is not null and pcode IN (${peo_codes.join(',')}) ORDER BY createtime `;
      fileList = await Exec(execsql);
     }
    list = _.map(list, function (item) {
      item = _.omit(item, 'openid', 'appcode', 'session_key', 'idcard', 'idcard_father');
      if (item.name_father) {
        let peoname = item.name_father;
        if (item.name && peoname != item.name) {
          peoname += '(' + item.name + ')';
        }
        item.name = peoname;
      }

      item.createtime = formatDateTime(item.createtime);
      item.updatetime = formatDateTime(item.updatetime);
      item.birthday = formatDate(item.birthday);
      let pp1 = _.find(plist, function (p) {
        return p.code == item.inviter_code;
      });
      let pp2 = _.find(plist, function (p) {
        return p.code == item.invitcode;
      });
      item.yname = pp1? pp1.name: '';
      if(pp1 && pp1.is_father){
        item.yname = pp1.name_father;
      }
      item.tname = pp2? pp2.name :'';
      if(pp2 && pp2.is_father){
        item.tname = pp2.name_father;
      }

      let photos = _.filter(fileList, function(a){
        return a.pcode==item.code;
      });
      item.photos = photos;
      return item;
    })
    let total = (await ExecGetOne(sql_count)).total;
    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    logger.error('------------peopleListBack----------------error,', error)
    return {
      code: 1,
      msg: '获取失败'
    }
  }
}
// 获取用户详情
const peopleQueryOne = async function (doc) {
  try {
    logger.info('------------peopleQueryOne----------------doc', doc)
    if (!doc.code) {
      return {
        code: 1,
        msg: 'code参数不能为空'
      }
    }
    let peopleData = await QueryOne('hzz_peoples', { code: doc.code }, 'state,visterstate,avator,qywx,code,name,nickname,level,age,grender,birthday,star,height,weight,cross_realname_auth,cross_work_auth,cross_education_auth,marital_status,education,university,company,position,year_income,inviter_wechat_code,isinviter,province,city,area,town,province_town,city_town,area_town,province_account,city_account,area_account,phone,isopen,islook,issecret,isschool,iscompany,islocal,is_father,relationship,identity,soldier,statu,invitcode,issave,house,car,marry,synopsis,online');
    if (!peopleData || peopleData.level==99) {
      logger.info('------------peopleQueryOne--------用户已注销-------doc', doc)
      return {
        code: 1,
        msg: '用户已注销'
      };
    }
    let result = peopleData;
    // 获取当前用户文件
    let execsql = `SELECT * FROM hzz_ossfiles WHERE pcode= '${peopleData.code}' ORDER BY createtime `;
    let fileList = await Exec(execsql);
    // 获取用户描述
    let peopleDes = await persondesList({ pcode: peopleData.code });
    // 获取用户标签
    //let peopleLabel = await personlabelQueryOne(peopleData.code);
    // 绑定描述图片
    _.map(peopleDes, function (item) {
      let imgs = _.filter(fileList, function (file) {
        return item.type == file.type && file.pcode == item.pcode;
      });
      if (imgs && imgs.length) {
        item.imgs = _.pluck(imgs, 'url');
      }
      result[item.type] = {
        type: item.type,
        remarks: item.remarks,
        imgs: item.imgs || []
      };
    })
    if (!result.self_description) {
      result['self_description'] = {
        type: 'self_description',
        remarks: '',
        imgs: []
      };
    }
    if (!result.ideal_partner) {
      result['ideal_partner'] = {
        type: 'ideal_partner',
        remarks: '',
        imgs: []
      };
    }
    // 绑定用户标签
    // if (peopleLabel) {
    //   result.my_label = _.omit(peopleLabel, 'pcode,createtime,updatetime');
    // }
    // 绑定相册
    result.photo = _.pluck(_.filter(fileList, function (fl) {
      return fl.type == '个人相册' && fl.url && fl.pcode == result.code;
    }), 'url');

    // 获取推荐人审批状态
    result.viterState = result.visterstate;
    // let his_data = await QueryOne('hzz_inviterhistories', { pcode: doc.code }, 'ispass');
    // if (his_data) {
    //   result.viterState = his_data.ispass;
    // }
    result.birthdayStr = formatDateYear(result.birthday);
    result.birthday = formatDate(result.birthday);
    //现居：adress-深圳南山区，户口：residence-湖北十堰，家乡：hometown-湖南长沙
    result.adress = '';
    if (result.city) {
      result.adress += result.city.replace('市', '');
      result.adress += result.area;
    }
    // 户籍地
    result.residence = '';
    if (result.province_account) {
      if (result.province_account == result.city_account) {
        result.residence += result.province_account.replace('市', '·');
        result.residence += result.area_account;
      } else {
        result.residence += result.province_account.replace('省', '·');
        result.residence += result.city_account.replace('市', '');
      }
    }
    // 家乡
    result.hometown = '';
    if (result.province_town) {
      if (result.province_town == result.city_town) {
        result.hometown += result.province_town.replace('市', '·');
        result.hometown += result.area_town;
      } else {
        result.hometown += result.province_town.replace('省', '·');
        result.hometown += result.city_town.replace('市', '');
      }
    }
    if (doc.pcode && doc.pcode != doc.code) {
      if (result.identity == '家长') {
        result.nickname = result.name_father ? result.name_father : result.nickname;
      }
      if (result.nickname && result.nickname.length > 6) {
        result.nickname = result.nickname.substr(0, 6);
      }
      result.nickname += `(${result.is_father ? '家长' : '本人'})`;
      // 添加访客记录
      accessrecordAdd({ pcode: doc.code, accesscode: doc.pcode });
      // 获取是否关注
      result.isfans = 0;
      let isfans_data = await QueryOne('hzz_peoplefans', { pcode: doc.code, fcode: doc.pcode }, 'state');
      if (isfans_data && isfans_data.state) {
        result.isfans = 1;
      }
      // 获取恋爱标准
      result.matchset = await ExecGetOne(`select * from hzz_matchsets where pcode='${doc.code}'`) || {
        age: (Number(result.age) - 7) + '-' + (Number(result.age) + 7),
        height: (Number(result.height) - 15) + '-' + (Number(result.height) + 15),
        city: result.city,
        education: '高中以上',
        marital_status: '未婚',
        preference: 0
      };

      // 不是同一人启用隐私管理
      if (result.isschool) {
        result.university = '******';
      }
      if (result.iscompany) {
        result.company = '******';
      }
      if (result.islocal) {
        result.province = '******';
        result.city = '******';
        result.province_town = '******';
        result.city_town = '******';
        result.province_account = '******';
        result.city_account = '******';
        result.native = '******';
      }
      // 相册不公开，获取有没有申请过，是否通过
      if (result.islook) {
        let tododata = await QueryOne('hzz_tasktodos', { name: '相册解锁', pcode: doc.code, gcode: doc.pcode });
        if (tododata) {
          if (tododata.status == 0) {
            result.islook = 2;// 申请中
          } else if (tododata.status == 1) {
            result.islook = 0;
          } else if (tododata.status == 2) {
            result.islook = 3; //申请被拒绝
          }
        }
        if (doc.pcode == result.invitcode) {
          result.islook = 0;
        }
      }
      result.university = result.university || '';
      result.position = result.position || '';
    }
    // 获取当前用户信息
    let myinfo = await QueryOne('hzz_peoples', { code: doc.pcode }, 'nickname,name,avator,code,isinviter,level,invitcode');
    if (myinfo && myinfo.isinviter) {
      myinfo.invitcode = myinfo.code;
    }
    result.myinfo = myinfo;
    // 获取推荐人简介
    // 自己是推荐人取自己的简介
    // if (result.isinviter) {
    //   result.synopsis = result.synopsis ? result.synopsis : '推荐人简介正在生成中...';
    //   result.invitername = result ? result.nickname : '';
    //   result.inviter = {
    //     nickname: result.nickname,
    //     code: result.code,
    //   };
    // } else {
    let invitData = await QueryOne('hzz_peoples', { code: result.invitcode }, 'synopsis,nickname,avator,code');
    let invitDataInfo = await QueryOne('hzz_inviterhistories', { pcode: result.invitcode }, 'description,nickname');
    invitData = invitData||{};
    if(invitDataInfo){
      result.synopsis = invitDataInfo.description;
      result.invitername = invitDataInfo.nickname;
      invitData.nickname = invitDataInfo.nickname;
      invitData.synopsis = invitDataInfo.description;
    } 
    // 格式化relationship
    result.inviter = invitData;
    if (doc.pcode && doc.pcode != doc.code) {
      let relationship = '';
      if (invitData) {
        relationship += invitData.nickname;
      }
      if (result.relationship && relationship.length<8) {
        relationship += '的' + result.relationship;
      }
      result.relationship = relationship;
    }
    // }
    if (doc.type == 'inviter') {
      result.inviter_info = await QueryOne('hzz_inviterhistories', { pcode: doc.code }, null);
    }
    // 用户没有头像，采用默认头像
    if (!result.avator) {
      result.avator = result.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
    }

    // logger.info('------------peopleQueryOne----------------result', result)
    return {
      code: 0,
      data: result
    }
  } catch (error) {
    logger.error('------------peopleQueryOne----------------error', error)
    return {
      code: 1,
      msg: error ? error.message : '获取失败'
    }
  }
}
// 获取用户详情-后台专用
const peopleQueryOneBack = async function (doc) {
  try {
    logger.info('------------peopleQueryOneBack----------------', doc)
    if (!doc.code) {
      return {
        code: 1,
        msg: 'code参数不能为空'
      }
    }
    let peopleData = await QueryOne('hzz_peoples', { code: doc.code }, '*');
    if(!peopleData){
      return {
        code: 1,
        msg: '用户已注销'
      };
    }
    peopleData.phone = peopleData.phone || peopleData.phone_bak;
    peopleData.createtime = formatDateTime(peopleData.createtime);
    peopleData.updatetime = formatDateTime(peopleData.updatetime);
    peopleData.birthday = formatDate(peopleData.birthday);
    // 获取当前用户文件
    let execsql = `SELECT * FROM hzz_ossfiles WHERE pcode= '${peopleData.code}' ORDER BY createtime `;
    let fileList = await Exec(execsql);
    // 获取用户描述
    let peopleDes = await persondesList({ pcode: peopleData.code });
    // 获取用户标签
    let peopleLabel = await personlabelQueryOne(peopleData.code);
    let result = _.omit(peopleData, 'wechat_code,openid,appcode,session_key,device,invitcode,address,validation,loginip,longitude,latitude,createtime,updatetime,sortnum,idcard,idcard_father');
    // 绑定描述图片
    // 绑定描述图片
    _.map(peopleDes, function (item) {
      let imgs = _.filter(fileList, function (file) {
        return item.type == file.type && file.pcode == item.pcode;
      });
      if (imgs && imgs.length) {
        item.imgs = _.pluck(imgs, 'url');
      }
      result[item.type] = {
        type: item.type,
        remarks: item.remarks,
        imgs: item.imgs || []
      };
    })
    if (!result.self_description) {
      result['self_description'] = {
        type: 'self_description',
        remarks: '',
        imgs: []
      };
    }
    if (!result.ideal_partner) {
      result['ideal_partner'] = {
        type: 'ideal_partner',
        remarks: '',
        imgs: []
      };
    }
    // 绑定用户标签
    if (peopleLabel) {
      result.my_label = _.omit(peopleLabel, 'pcode,createtime,updatetime');
    }
    // 绑定相册
    result.photo = _.filter(fileList, function (fl) {
      return fl.type == '个人相册' && fl.url && fl.pcode == result.code;
    });
    // 关联邀请人
    // result.inviterphone='';
    // if(result.inviter_code){
    //   let interData = await QueryOne('hzz_peoples',{code: result.inviter_code}, 'phone');
    //   if(interData){
    //     result.inviterphone = interData.phone;
    //   }
    // }

    return {
      code: 0,
      data: result
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取失败'
    }
  }
}

const peopleUpdate = async function (doc) {
  try {
    if (!doc.id) {
      let userdata = await QueryOne('hzz_peoples', { code: doc.pcode }, 'id, level, isinviter, code,cross_education_auth, cross_realname_auth, cross_work_auth');
      doc.id = userdata.id;
      if(userdata.level==19 && doc.visterstate==2){
        doc.level = 1;
      }
    }

    doc = filObj(doc);
    let newdoc = format(doc);
    // 如果是实名认证，发现已导入过，同步导入信息至新账号--todo
    // if(doc.idcard){
    //   syncoldPeoToNew(doc.pcode, doc.idcard);
    // }
    await Update('hzz_peoples', newdoc);
    return {
      code: 0,
      msg: '人员更新成功'
    }
  } catch (error) {
    logger.error('-----------peopleUpdate---error-', error)
    return {
      code: 1,
      msg: '人员更新异常'
    }
  }
}
// 如果是实名认证，发现已导入过，同步导入信息至新账号
async function syncoldPeoToNew(oldCode, idcard){
  let importUser = await ExecGetOne(`select * from hzz_peoples where idcard='${doc.idcard}' and code<> '${doc.code}'`);
  if(importUser){
    newdoc = _.extend(newdoc, _.omit(importUser,['_id','code','name','birthday','age','star','grade','cross_realname_auth','reliability','idcard_father','name_father','createtime','updatetime']))
    
  }
}
// 导入用户
const peopleImport = async function (req) {
  try {
    let files = getfilePath(req);
    logger.info('-----------peopleImport---files-', files)
    if (files && files.length) {
      let datalist = xlsxParse(files[0].path);
      logger.info('-----------peopleImport---datalist-', JSON.stringify(datalist))
      if (datalist && datalist.length) {
        for (let i = 0; i < datalist.length; i++) {
          let item_imp = datalist[i];
          logger.info('-----------peopleImport---item_imp-', item_imp)
          // 用户描述信息
          let people_des = {
            self_description: item_imp.self_description,
            ideal_partner: item_imp.ideal_partner
          };
          //  _.pick(item_imp, 'self_description,family_back,hobby,ideal_partner');
          logger.info('-----------peopleImport---people_des-', people_des)
          // 用户基本信息
          delete item_imp.self_description;
          delete item_imp.family_back;
          delete item_imp.hobby;
          delete item_imp.ideal_partner;
          let item = item_imp;// _.omit(item_imp, 'self_description,family_back,hobby,ideal_partner');
          logger.info('-----------peopleImport---item-', item)
          // 匹配推荐人-根据推荐人手机号
          if(item_imp.inviter_wechat_code){
            let vidata = await QueryOne('hzz_peoples', { phone: item_imp.inviter_wechat_code });
            if(vidata){
              item.invitcode = vidata.code;
            }
          }
         
          item.cross_realname_auth = 1;
          item.confirm = 1;
          if (item.phone) {
            let ispeo = await QueryOne('hzz_peoples', { phone: item.phone });
            if (ispeo) {
              item.id = ispeo.id;
              item.code = ispeo.code;
              peopleUpdate(item);
            } else {
              ispeo = await peopleCreate(init(item));
            }
            people_des.pcode = ispeo.code;
            // 关联用户图片
            ossfileUpdatePcode(ispeo.code, ispeo.name)
            // 保存用户描述信息
            logger.info('-----------peopleImport---people_des-', people_des)
            persondesImport(people_des);
          } else {
            if (item.name) {
              let ispeo = await QueryOne('hzz_peoples', { name: item.name });
              if (ispeo) {
                item.id = ispeo.id;
                item.code = ispeo.code;
                peopleUpdate(item);
              } else {
                ispeo = await peopleCreate(init(item));
              }
              people_des.pcode = ispeo.code;
              // 关联用户图片
              ossfileUpdatePcode(ispeo.code, ispeo.name)
              // 保存用户描述信息
              logger.info('-----------peopleImport---people_des-', people_des)
              persondesImport(people_des);
            } else {
              console.log(`----peopleImport--------导入用户--失败--${item.nickname}未填写手机号和姓名----`);
            }
          }
        }
        return {
          code: 0,
          msg: '用户信息上传成功'
        }
      } else {
        return {
          code: 1,
          msg: '请填写用户信息后上传'
        }
      }
    } else {
      return {
        code: 1,
        msg: '请选择图片上传'
      }
    }
  } catch (error) {
    logger.info('-----------peopleImport---error-', error)
    return {
      code: 1,
      msg: '导入用户异常'
    }
  }
}
// 创建用户
const peopleCreate = async function (doc) {
  return Add('hzz_peoples', init(doc));
}

// 导入用户
const peopleImport_hand = async function () {
  try {
    const ROOT_PATH = process.cwd();
    let filepath = ROOT_PATH + '/files/01a0e31d329c8d38c46cbaae3918c4ec.xlsx';
    let datalist = xlsxParse(filepath);
    if (datalist && datalist.length) {
      for (let i = 0; i < datalist.length; i++) {
        let item_imp = datalist[i];
        // 用户描述信息
        let people_des = {
          item_imp
        };
        _.pick(item_imp, 'self_description', 'family_back', 'hobby', 'ideal_partner');
        // 用户基本信息
        let item = _.omit(item_imp, 'self_description', 'family_back', 'hobby', 'ideal_partner');
        if (item.phone) {
          let ispeo = await QueryOne('hzz_peoples', { phone: item.phone });
          if (ispeo) {
            item.id = ispeo.id;
            item.code = ispeo.code;
            peopleUpdate(item);
          } else {
            ispeo = await peopleCreate(init(item));
          }
          people_des.pcode = ispeo.code;
          // 关联用户图片
          ossfileUpdatePcode(ispeo.code, ispeo.phone)
          // 保存用户描述信息
          persondesImport(people_des);
        } else {
          if (item.name) {
            let ispeo = await QueryOne('hzz_peoples', { name: item.name });
            if (ispeo) {
              item.id = ispeo.id;
              item.code = ispeo.code;
              peopleUpdate(item);
            } else {
              ispeo = await peopleCreate(init(item));
            }
            people_des.pcode = ispeo.code;
            // 关联用户图片
            ossfileUpdatePcode(ispeo.code, ispeo.name)
            // 保存用户描述信息
            persondesImport(people_des);
          } else {
            console.log(`----peopleImport--------导入用户--失败--${item.nickname}未填写手机号和姓名----`);
          }
        }
      }
      return {
        code: 0,
        msg: '用户信息上传成功'
      }
    } else {
      return {
        code: 1,
        msg: '请填写用户信息后上传'
      }
    }
  } catch (error) {
    return {
      code: 1,
      msg: '导入用户异常'
    }
  }
}

const peopleExecOne = async function (filter, select) {
  return QueryOne('hzz_peoples', filter, select);
}
// 我的用户
const peopleMyinviter = async function (doc) {
  try {
    logger.info(`-------peopleMyinviter------doc:`, doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '请退出小程序重新进入'
      }
    }
    let list = await Exec(`select phone,userstate,visterstate,id,code,nickname,name,name_father,avator,identity,grender,birthday,height,year_income,education,createtime,isinviter,online,relationship,remarks from hzz_peoples where invitcode='${doc.pcode}' AND length(code)=12 ORDER BY createtime DESC,id DESC`);// AND ((online=1 AND isinviter=0) OR isinviter=1 )
    list = _.map(list, function (item) {
      item.createtime = formatDateTime(item.createtime);
      item.birthday = formatDateYear(item.birthday);
      item.nickname = item.name ? item.name : (item.name_father ? item.name_father : item.nickname);
      if (item.identity == '家长') {
        item.nickname = item.name_father ? item.name_father : item.nickname;
      } else {
        item.nickname = item.name ? item.name : item.nickname;
      }
      if (item.nickname && item.nickname.length > 6) {
        item.nickname = item.nickname.substr(0, 6);
      }
      if(item.identity == '家长'){
        item.nickname+='（家长）';
      }
      // item.nickname+= '（'+item.identity == '家长'? '家长'+'）';
      item.userstate = item.userstate == 2 ? 9 : item.userstate;
      item.visterstate = item.visterstate == 2 ? 9 : item.visterstate;
      // 用户没有头像，采用默认头像
      if (!item.avator) {
        item.avator = item.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' : 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
      }
      // 更新用户状态为已读
      peopleUpdate({ id: item.id, isread: 1 });
      return item;
    })
    return {
      code: 0,
      data: list
    }
  } catch (error) {
    logger.info(`-------peopleMyinviter------error:`, error)
    return {
      code: 1,
      msg: error ? error.message : '获取失败'
    }
  }
}
// 情侣配对
const peopleCouplePair = async function (doc) {
  try {
    logger.info(`-------peopleCouplePair------doc:`, doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '请退出小程序重新进入'
      }
    }
    let returnList = [];
    let list = await Exec(`select name,nickname,code,avator,state,age,grender,createtime,birthday from hzz_peoples where invitcode='${doc.pcode}' and statu=1 order by createtime DESC,id ASC `);
    if (list && list.length) {
      let pcodestr = _.pluck(list || [], 'code');
      let peopleconList = await Exec(`select pcode,fcode,createtime from hzz_peoplecontacts where pcode in (${pcodestr.join(',')}) Order by createtime DESC`);
      let fcodestr = _.pluck(peopleconList || [], 'fcode');
      let fcodePeoList = await Exec(`select name,nickname,code,avator,state,age,grender from hzz_peoples where code in (${fcodestr.join(',')}) `);
      _.map(peopleconList, function (item) {
        let createtime = formatDateTime(item.createtime);
        let pinfo = _.find(list, function (pl) {
          return pl.code == item.pcode;
        });
        if (pinfo && pinfo.birthday)
          pinfo.birthday = formatDateYear(pinfo.birthday);
        let finfo = _.find(fcodePeoList, function (pl) {
          return pl.code == item.fcode;
        });
        if (finfo && finfo.birthday)
          finfo.birthday = formatDateYear(finfo.birthday);
        if (finfo && pinfo) {
          returnList.push({
            createtime,
            pinfo,
            finfo
          });
        }
      })
    }
    return {
      code: 0,
      data: returnList
    }
  } catch (error) {
    logger.info(`-------peopleCouplePair------error:`, error)
    return {
      code: 1,
      msg: error ? error.message : '获取失败'
    }
  }
}
// 定时更新用户推荐人code
const timerUpdateInvistcode = async function () {
  let list = await Exec(`select id,code,inviter_wechat_code from hzz_peoples where inviter_wechat_code is not null and invitcode is NULL`);
  for (const item of list) {
    if (item.inviter_wechat_code) {
      let data = await ExecGetOne(`select code from hzz_peoples where phone='${item.inviter_wechat_code}'`);
      if (data && data.code)
        await Exec(`update hzz_peoples set invitcode='${data.code}' where id=${item.id}`);
    }
  }
}
// 获取用户隐私管理
const peopleSecret = async function (pcode) {
  try {
    logger.info(`-------peopleSecret------pcode:`, pcode)
    if (!pcode) {
      return {
        code: 1,
        msg: '请退出小程序重新进入'
      }
    }
    let data = await QueryOne('hzz_peoples', { code: pcode }, 'isschool,iscompany,islocal,issecret,isopen,islook');
    return {
      code: 0,
      data: data
    }
  } catch (error) {
    return {
      code: 1,
      msg: '获取异常，请重试'
    }
  }
}
// 保存用户隐私设置
const peopleSecretEdit = async function (doc) {
  try {
    logger.info(`-------peopleSecretEdit------doc:`, doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '请退出小程序重新进入'
      }
    }
    let data = await QueryOne('hzz_peoples', { code: doc.pcode }, 'id');
    if (data) {
      doc.id = data.id;
      delete doc.pcode;
      logger.info(`-------peopleSecretEdit------Update:`, doc)
      await Update('hzz_peoples', format(doc));
    }
    return {
      code: 0,
      msg: '保存成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: '获取异常，请重试'
    }
  }
}
let authstate = {//0未认证，1认证通过，2：认证中，9认证失败
  0: '未认证',
  1: '已认证',
  2: '认证中',
  9: '认证失败',
};
// 导出用户列表
const peopleExport = async function (doc) {
  try {
    let { filter, select, pagenum, pagesize } = doc;
    let sql = `SELECT * FROM hzz_peoples  WHERE 1=1 `;
    let sql_filter = '';
    if (filter) {
      for (const key in filter) {
        if (Object.hasOwnProperty.call(filter, key)) {
          const val = filter[key];
          if (val) {
            if (key == 'nickname' || key == 'phone') {
              sql_filter += ` AND ${key} like '%${val}%' `;
            } else if (key == 'level') {
              sql_filter += ` AND ${key} >=${val}`
            } else {
              sql_filter += ` AND ${key} =${val}`
            }
          }
        }
      }
    }

    sql += sql_filter;
    sql += ' ORDER BY sortnum ASC ,updatetime DESC ';
    let datalist = await Exec(sql);
    let list = [['昵称', '姓名', '性别', '生日', '年龄', '手机号码', '微信号', '推荐人手机号', '学历', '身高', '体重', '婚姻状况', '省', '市', '区', '籍贯省', '籍贯市', '籍贯区', '学历认证', '实名认证', '工作认证', '推荐人昵称', '邀请人昵称', '是否家长', '平台是否公开', '主页是否公开', '用户来源', '创建时间']];

    // 获取推荐人邀请人昵称
    let pcodes = _.compact(_.union(_.pluck(datalist, 'inviter_code'), _.pluck(datalist, 'invitcode')));
    let plist = await Exec(`select nickname from hzz_peoples where code in (${pcodes.join(',')})`);
    _.map(datalist, function (item) {
      let obj = [];
      item.createtime = formatDate(item.createtime);
      item.birthday = formatDateYear(item.birthday);
      let pp1 = _.find(plist, function (x) {
        return x.code == item.inviter_code;
      })
      let pp2 = _.find(plist, function (x) {
        return x.code == item.invitcode;
      })
      obj.push(item.nickname, item.name, item.grender, item.birthday, item.age, item.phone, item.wechat_code, item.inviter_wechat_code, item.education, item.height, item.weight, item.marital_status, item.province, item.city, item.area, item.province_town,
        item.city_town, item.area_town, authstate[item.cross_education_auth], authstate[item.cross_realname_auth], authstate[item.cross_work_auth], pp2 ? pp2.nickname : '', pp1 ? pp1.nickname : '', item.is_father ? '是' : '否', item.isopen ? '否' : '是', item.islook ? '否' : '是', item.sourcetype, item.createtime);
      list.push(obj);
    })
    let portList = [
      {
        name: "用户列表",
        data: list
      }
    ]
    return await exportParse(portList, '用户列表');
  } catch (error) {
    return {
      code: 1,
      msg: '导出失败'
    }
  }
}
// 用户发布/回收-后台
const peopleSend = async function (doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: '请勾选用户'
      }
    }
    let up = {
      id: doc.id,
      online: doc.online
    };
    let people = await QueryById('hzz_peoples', doc.id);
    if(people.level==99){
      return {
        code: 1,
        msg: '用户已注销，发布失败'
      }
    }
    if (!people.confirm) {
      return {
        code: 1,
        msg: '用户未确认，发布失败'
      }
    }
    if (people.online == 1 && doc.online == 1) {
      return {
        code: 1,
        msg: '用户已发布，无需再次发布'
      }
    }
    if (people.online == 2 && doc.online == 2) {
      return {
        code: 1,
        msg: '用户已回收，无需再次回收'
      }
    }
    up.userstate = doc.online;
    if (doc.online == 1) {
      if (people.isinviter) {
        up.level = 19;
      } else {
        up.level = 1;
      }
    } else {
      if (people.level == 19) {
        up.level = 9;
      } else if (people.level == 1) {
        up.level = 0;
      }
    }
    await Update('hzz_peoples', format(up));
    return {
      code: 0,
      msg: doc.online == 1 ? '发布成功' : '回收成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: (doc.online == 1 ? '发布' : '回收') + '异常，请重试'
    }
  }
}
// 设置推荐人
const peopleSet = async function (doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: 'id参数未传'
      }
    }
    let up = {
      id: doc.id,
      synopsis: doc.synopsis
    };
    await Update('hzz_peoples', format(up));
    return {
      code: 0,
      msg: '设置成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: '设置异常，请重试'
    }
  }
}
// 取消置顶
const peopleNoTop = async function (doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: 'id参数未传'
      }
    }
    let up = {
      code: doc.id,
      sortnum: 999,
      topstate: 0
    };
    let peo = await QueryOne('hzz_peoples', { code: doc.id });
    if (peo.topstate != 1) {
      return {
        code: 1,
        msg: '此用户未置顶，无需取消置顶'
      }
    }
    up.id = peo.id;
    await Update('hzz_peoples', format(up));
    return {
      code: 0,
      msg: '取消置顶成功'
    }
  } catch (error) {
    logger.error('----peopleNoTop-----取消置顶异常，请重试:', error);
    return {
      code: 1,
      msg: '取消置顶异常，请重试'
    }
  }
}
// 相册解锁
const UnLock = async function (doc) {
  try {
    // 创建待办任务
    let { code, fcode } = doc;
    if (!code || !fcode) {
      logger.error('----UnLock-----申请失败，请联系客服,doc:', doc);
      return {
        code: 0,
        msg: '申请失败，请联系客服'
      }
    }
    // 判断是否申请过，不能重复申请
    let isdata = await QueryOne('hzz_tasktodos', { pcode: code,gcode: fcode }, null);
    if(isdata){
      return {
        code: 0,
        msg: '申请已发送，等待对方通过'
      }
    }
    taskAdd({ name: '相册解锁', pcode: code, gcode: fcode });
    let fuser = await QueryOne('hzz_peoples', { code: fcode }, 'nickname');
    if (fuser) {
      // 发送提醒消息 
      let send_data = {
        "first": {
          "value": "您好，你有新的待办需要处理！",
          "color": "#173177"
        },
        "keyword1": {
          "value": "相册申请消息",
          "color": "#173177"
        },
        "keyword2": {
          "value": `收到[${fuser.nickname}]的相册申请消息 `,
          "color": "#e8320e"
        },
        "remark": {
          "value": "点击查看并处理",
          "color": "#173177"
        }
      };
      let send_data_red = {
        "thing2": {
          "value": `收到[${fuser.nickname}]的相册申请消息 `
        },
        "time1": {
          "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
        }
      };
      sendMsg('photo_tmpid', send_data, code, "pages/message/message",send_data_red);
    }
    return {
      code: 0,
      msg: '申请已发送，等待对方通过'
    }
  } catch (error) {
    logger.error('----UnLock-----相册解锁异常，请重试,error:', error);
    return {
      code: 1,
      msg: '相册解锁异常，请重试'
    }
  }
}
// 校验用户资料填写完整度
async function validatePeopleInfo() {
  try {
    let list = await Exec(`select code,openid from hzz_peoples where isinviter=0 AND online=0 AND block=0 AND (university='' OR company='' OR position='' OR cross_realname_auth IN (0,9) OR phone IS NULL OR avator IS NULL OR nickname like'红豆用户%' OR nickname like'豆号%') `);
    for (let i = 0; i < list.length; i++) {
      const user = list[i];
      if (user && user.code && user.openid) {
        // 发送提醒消息 
        let send_data = {
          "first": {
            "value": "您好，您的业务有新进展！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "资料填写提醒",
            "color": "#173177"
          },
          "keyword2": {
            "value": "您好，红豆家缘提醒您完善个人资料，平台第一时间审核后，将您推荐给其他单身用户。",
            "color": "#e8320e"
          },
          "remark": {
            "value": "前往'我的-编辑'填写，感谢您的支持！",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": "您好，红豆家缘提醒您完善个人资料，平台第一时间审核后，将您推荐给其他单身用户。"
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        logger.info('--校验用户资料填写完整度------validatePeopleInfo--,send_data', send_data);
        sendMsg('validate_info', send_data, user.code, "pages/message/message",send_data_red);
      }
    }
  } catch (error) {
    logger.info('--校验用户资料填写完整度------validatePeopleInfo--,error', error);
  }
}

async function saveRemarks(doc){
  try {
    let {id, remarks } = doc;
    if(!id){
      return {
        code:1,
        msg:'缺失参数id'
      };
    }
    let isdone = await Exec(`update hzz_peoples set remarks = '${remarks}' where id=${id}`);
    return {
      code:0,
      msg:'备注成功'
    }; 
  } catch (error) {
    return {
      code:1,
      msg:'备注失败'
    };
  }
}

async function initGrade(){
  let userlist = await Query('hzz_peoples',null,null);
  for (let index = 0; index < userlist.length; index++) {
    const user = userlist[index];
    let grade=0;
    if(user.phone){
      grade++;
    }
    if(user.avator != 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png' && user.avator != 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png'){
      grade++;
    }
    if(user.cross_realname_auth ==1){
      grade++;
    }
    if(user.confirm ==1){
      grade++;
    }
    await Update('hzz_peoples', {id: user.id, grade: grade});
  }
}

module.exports = {
  peopleSave,
  peopleSaveBack,
  peopleList,
  peopleListBack,
  peopleQueryOne,
  peopleQueryOneBack,
  peopleUpdate,
  peopleCreate,
  peopleImport,
  peopleImport_hand,
  peopleExecOne,
  peopleMyinviter,
  peopleCouplePair,
  timerUpdateInvistcode,
  peopleSecret,
  peopleSecretEdit,
  peopleExport,
  peopleSend,
  peopleNoTop,
  peopleSet,
  validatePeopleInfo,
  UnLock,
  saveRemarks,
  initGrade
}